<?php

namespace App\Console\Commands;

use App\Models\User;
use Illuminate\Console\Command;
use DB;
use EasyWeChat;

class SellOrderAutoCheck extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'book-shop:sell-order-auto-check';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '订单自动审核通过';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->info("开始获取...");

        //一次审核时，在用户预约上门取件的时间前2小时，订单还未审核（包括审核通过、审核不通过）的情况下，自动执行审核通过操作
        $orders = DB::table('sell_orders')->where('state',1)->get();
        if(!empty($orders))
        {
            foreach ($orders as $v)
            {
                $time = $v->express_time - time();
                if($time <= 10800)
                {
                    //构造在线下单提交信息
                    $eorder = [];
                    $eorder["ShipperCode"] = "SF";
                    $eorder["OrderCode"] = $v->no;
                    $eorder["PayType"] = 2;  //1-现付，2-到付，3-月结，4-第三
                    $eorder["ExpType"] = 2;
                    $eorder["StartDate"] = date('Y-m-d H:i:s',$v->express_time);

                    $sender = [];
                    $sender["Name"] = $v->deliver_name;
                    $sender["Mobile"] = $v->deliver_mobile;
                    $sender["ProvinceName"] = $v->deliver_address_province;
                    $sender["CityName"] = $v->deliver_address_city;
                    $sender["ExpAreaName"] = $v->deliver_address_area;
                    $sender["Address"] = $v->deliver_address_detail;

                    $receiver = [];
                    $receiver["Name"] = "快鱼二手书（请发特惠件或大件）";
                    $receiver["Mobile"] = "15888825922";
                    $receiver["ProvinceName"] = "浙江省";
                    $receiver["CityName"] = "杭州市";
                    $receiver["ExpAreaName"] = "余杭区";
                    $receiver["Address"] = "万科未来城二期21-1-2302";

                    $commodityOne = [];
                    $commodityOne["GoodsName"] = "图书";
                    $commodity = [];
                    $commodity[] = $commodityOne;

                    $eorder["Sender"] = $sender;
                    $eorder["Receiver"] = $receiver;
                    $eorder["Commodity"] = $commodity;

                    //调用在线下单
                    $jsonParam = json_encode($eorder, JSON_UNESCAPED_UNICODE);
                    $jsonResult = $this->_submitOrder($jsonParam);

                    //解析在线下单返回结果
                    $result = json_decode($jsonResult, true);
                    if($result['Success'] && $result['ResultCode'] == 100)
                    {
                        DB::table('sell_orders')->where('id',$v->id)->update([
                            'state'             => 2,
                            'is_express'        => 1,
                            'express_no'        => $result['Order']['LogisticCode'],
                            'shipper_code'      => $result['Order']['ShipperCode'],  //快递公司编码
                            'express_order_no'  => $result['Order']['OrderCode'],
                            'check_time'        => time(),
                        ]);

                        DB::table('sell_order_items')->where('sell_order_id',$v->id)->update(['first_check_state'=>1]);
                        $sms = app('easysms');
                        try {
                            $sms->send($v->deliver_mobile,[
                                'template' => 'SMS_163051059',
                                'data' => [
                                    'name' => $v->deliver_name,
                                    'time' => date('Y-m-d H:i',$v->express_time),
                                ],
                            ]);
                        } catch (\Overtrue\EasySms\Exceptions\NoGatewayAvailableException $exception) {
                            $message = $exception->getException('aliyun')->getMessage();
                            dd($message);
                        }

                        //发送模板消息
                        $officialAccount = EasyWeChat::officialAccount(); // 公众号
                        $user = User::query()->select(['id','wechat_openid','unionid'])->where('id',$v->user_id)->first();
                        $wechat_user = \DB::table('wechat_users')->where('unionid',$user->unionid)->first();
                        if(!empty($wechat_user))
                        {
                            $openid = $wechat_user->openid;

                            $express_time = date('Y-m-d H:i',$v->express_time);
                            $first = "卖书订单通过审核，已安排快递上门取书\r\n"."顺丰快递将于你预约的时间：{$express_time}免费上门取书。在预约的时间前1小时内您会收到顺丰的短信，请留意短信通知。\r";
                            $officialAccount->template_message->send([
                                'touser'        => $openid,
                                'template_id'   => 'fDri6AUO73KHgibmDn8v8vm1esCaNMCML_eesYlb6Ns',
                                'url'  => '',
                                'miniprogram' => [
                                    'appid'     => config('wechat.mini_program.default.app_id'),
                                    'path'  => '/pages/sale/order/order-detail/order-detail?id='.$v->id,
                                ],
                                'data' => [
                                    'first'         => $first,
                                    'OrderSn'       => $v->no,
                                    'OrderStatus'   => '已安排快递上门取书'."\r\n",
                                    'remark'        => '请提前将要卖的书打包好，如需更改快递上门时间，请在快递员联系你时，直接告知快递员新的上门取件时间即可。'
                                ],
                            ]);
                        }

                    }
                }
            }
        }



        $this->info("获取成功...");
    }

    private function _submitOrder($requestData)
    {
        //$url = 'http://testapi.kdniao.cc:8081/api/oorderservice';
        $url = 'http://api.kdniao.com/api/eorderservice';
        $ebusinessid = '1363157';
        $appkey = 'f426aae4-89fa-4a90-863c-08c96328b7f6';
        $datas = array(
            'EBusinessID' => $ebusinessid,
            'RequestType' => '1001',
            'RequestData' => urlencode($requestData) ,
            'DataType' => '2',
        );
        $datas['DataSign'] = kdniao_encrypt($requestData, $appkey);

        $result = sendPost($url, $datas);

        //根据公司业务处理返回的信息......

        return $result;
    }
}
